package org.fjsei.yewu.util;

import jakarta.servlet.http.HttpServletRequest;
import org.fjsei.yewu.security.DeviceInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * 设备信息提取工具类
 */
@Component
public class DeviceInfoExtractor {

    private static final String DEVICE_ID_HEADER = "X-Device-Id";
    private static final String DEVICE_TYPE_HEADER = "X-Device-Type";
    private static final String DEVICE_NAME_HEADER = "X-Device-Name";

    /**
     * 从HTTP请求中提取设备信息
     */
    public DeviceInfo extractDeviceInfo(HttpServletRequest request) {
        String deviceId = request.getHeader(DEVICE_ID_HEADER);
        String deviceType = request.getHeader(DEVICE_TYPE_HEADER);
        String deviceName = request.getHeader(DEVICE_NAME_HEADER);
        String userAgent = request.getHeader("User-Agent");
        String ipAddress = getClientIpAddress(request);

        // 如果前端没有提供设备ID，生成一个
        if (!StringUtils.hasText(deviceId)) {
            deviceId = UUID.randomUUID().toString();
        }

        // 如果没有提供设备类型，尝试从User-Agent推断
        if (!StringUtils.hasText(deviceType)) {
            deviceType = inferDeviceType(userAgent);
        }

        // 如果没有提供设备名称，使用默认值
        if (!StringUtils.hasText(deviceName)) {
            deviceName = deviceType + " Device";
        }

        return DeviceInfo.builder()
                .deviceId(deviceId)
                .deviceType(deviceType)
                .deviceName(deviceName)
                .userAgent(userAgent)
                .ipAddress(ipAddress)
                .lastActiveTime(System.currentTimeMillis())
                .build();
    }

    /**
     * 从User-Agent推断设备类型
     */
    private String inferDeviceType(String userAgent) {
        if (userAgent == null) {
            return "UNKNOWN";
        }

        userAgent = userAgent.toLowerCase();

        if (userAgent.contains("mobile") || userAgent.contains("android")) {
            return "MOBILE_ANDROID";
        } else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
            return "MOBILE_IOS";
        } else if (userAgent.contains("electron")) {
            return "DESKTOP";
        } else {
            return "WEB";
        }
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_FORWARDED",
                "HTTP_X_CLUSTER_CLIENT_IP",
                "HTTP_CLIENT_IP",
                "HTTP_FORWARDED_FOR",
                "HTTP_FORWARDED",
                "HTTP_VIA",
                "REMOTE_ADDR"
        };

        for (String header : headers) {
            String ip = request.getHeader(header);
            if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个IP值，第一个IP才是真实IP
                int index = ip.indexOf(',');
                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            }
        }

        return request.getRemoteAddr();
    }
}
